// Package middleware provides enhanced middleware with dependency injection
package middleware

import (
	"gitee.com/zhenyangze/gin-framework/internal/pkg/container"
	"gitee.com/zhenyangze/gin-framework/internal/pkg/logger"
	"github.com/gin-gonic/gin"
)

// ContainerKey is the context key for the dependency container
const ContainerKey = "container"

// WithContainer adds the dependency container to the gin context
func WithContainer(container *container.Container) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Set(ContainerKey, container)
		c.Next()
	}
}

// GetContainer retrieves the dependency container from gin context
func GetContainer(c *gin.Context) *container.Container {
	if containerInterface, exists := c.Get(ContainerKey); exists {
		if ctr, ok := containerInterface.(*container.Container); ok {
			return ctr
		}
	}
	// Fallback to global container for backward compatibility
	return container.GetContainer()
}

// WithRequestContext creates a context with request information
func WithRequestContext() gin.HandlerFunc {
	return func(c *gin.Context) {
		ctx := c.Request.Context()

		// Add request ID if available
		if requestID := c.GetString("X-Request-ID"); requestID != "" {
			ctx = logger.WithRequestID(ctx, requestID)
		}

		// Add user ID if available from JWT
		if userID := c.GetString("user_id"); userID != "" {
			ctx = logger.WithUserID(ctx, userID)
		}

		// Update request with enhanced context
		c.Request = c.Request.WithContext(ctx)
		c.Next()
	}
}

// GetLogger retrieves a context-aware logger
func GetLogger(c *gin.Context) logger.Logger {
	container := GetContainer(c)
	if container == nil {
		return nil
	}

	log := container.Logger()
	if log == nil {
		return nil
	}

	// Add request context
	return log.WithContext(c.Request.Context())
}